﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartParking.Server.IConfiguration;
using SmartParking.Server.IService;
using SmartParking.Server.Models;
using SmartParking.Server.Modules;
using SmartParking.Server.Service;
using System.Text.Json;

namespace SmartParking.Server.Start.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ILoginService _loginService;
        private readonly IMenuService _menuService;
        private readonly IUserService _userService;
        private readonly IUtils _utils;

        public UserController(ILoginService loginService, IMenuService menuService, IUserService userService, IUtils utils)
        {
            this._loginService = loginService;
            this._menuService = menuService;
            this._userService = userService;
            this._utils = utils;
        }
        [HttpPost]
        public IActionResult Login([FromForm] string username, [FromForm] string password) 
        {
            //return "{\"name\":"+ username + "}";
            var users = _loginService.Query<SysUserInfo>(u => u.UserName == username && u.Password == password);
            if (users.Count() > 0)
            {
                SysUserInfo sysUserInfo = users.ToList()[0];
                // 菜单               
                // 权限管理
                List<MenuInfo> menus = _menuService.GetMenusByUserId(sysUserInfo.UserId);
                sysUserInfo.Menus = menus;
                return Ok(sysUserInfo);
            }
            else {
                return NoContent();
            }
        }

        [HttpGet]
        public IActionResult GetUsers()
        {
            var users = _userService.Query<SysUserInfo>(x=>true);
            return Ok(users);
        }

        //[HttpGet("roles/{userId}")]
        //public JsonResult GetRolesByUserId(int userId)
        //{
        //    return Json(_userService.GetRolesByUserId(userId));
        //}

        [HttpPost]
        [Route("resetpwd")]
        public IActionResult ResetPassword([FromForm] IFormCollection form)
        {
            _userService.ResetPassword(int.Parse(form["userId"]));
            return Ok();
        }

        [HttpPost]
        [Route("save")]
        public IActionResult UpdateUserInfo([FromBody] JsonElement data)
        {
            _userService.SaveUser(data.ToString());
            return Ok(data);
        }
    }
}
